package com.smm.web.mtower.bo;

import com.smm.web.mtower.domain.Camera;
import com.smm.web.mtower.domain.TagAlamEvent;
import com.smm.web.mtower.util.ImageUtil;
import com.smm.web.mtower.util.MapUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;

/**
 * Created by zhenghao on 2016/6/13.
 *
 */
@Service
public class EventBO {

    private Logger logger= Logger.getLogger(this.getClass());

    @Value("${image.save.path}")
    private String imageSavePath;    //抓拍图片保存路径


    @Resource
    private CameraBO cameraBO;


    @Resource
    private RemoteBO remoteBO;

    /**
     * 处理报警事件
     * @param event
     */
    public void disposeAlamEvent(TagAlamEvent event) throws Exception{

        logger.info("开始处理报警信息。 TagId："+event.getTagId() +" time:"+event.getTime());

        //1.检查是否是重复报警（30秒内）
        boolean isReplayAlam = checkIsReplay(event.getTagId());

        logger.info("是否30秒内重复报警："+ isReplayAlam);

        if(isReplayAlam) return;

        //2.通过标签编号找到对应摄像头
        Camera camera = getCameraByTag(event.getTagId());

        if(camera == null){

            logger.info("未找到对应摄像头信息。 tag："+event.getTagId());

            return ;
        }

        logger.info("开始抓拍图片. camera:"+camera.getIp());

        //3.调用摄像头抓，保存抓拍图片
        String imageName= event.getTime().getTime()+".jpg";

        cameraBO.sanp(camera,imageSavePath+imageName);

        logger.info("开始压缩图片，0.4倍压缩");

        //4.压缩抓拍图片
        ImageUtil.reduce(imageSavePath,imageName);

        logger.info("提交报警事件给服务器");
        //5.报警事件上传给服务器
        event.setImageName(imageName);

        remoteBO.post(event);

        logger.info("开始上传报警图片给服务器");
        //6.开始上传图片
        remoteBO.uploadImage(imageSavePath+imageName);


        logger.info("图片上传完成，删除本地图片");
        //7.上传完成，删除图片
        File  file = new File(imageSavePath + imageName);
        file.delete();

        logger.info("报警事件处理完成");

    }


    private Camera getCameraByTag(String tagId) {

        return MapUtil.TagAndCameraMap.get(tagId);
    }

    private boolean checkIsReplay(String tagId) {

        //清单内存区中所有保存时间超过30秒的记录
        cleanRecode();

        //通过tagid 检查是否还在内存区中存在。如果存在， 返回true
        if(MapUtil.TagAlamRecode.get(tagId) !=null){

            return true;
        }

        //不存在，保存标签记录,返回false
        MapUtil.TagAlamRecode.put(tagId,String.valueOf(new Date().getTime()));

        return false;
    }


    private void cleanRecode() {

        //获得30秒之前的时间

        //获得当前系统时间
        Date now = new Date();

        //获得30秒之前的时间
        String beforeTime = String.valueOf(now.getTime()-30*1000);

        Iterator<String> it = MapUtil.TagAlamRecode.keySet().iterator();

        //循环检查
        while (it.hasNext()){

            String tagId = it.next();

            String time = MapUtil.TagAlamRecode.get(tagId);

            //检查时间是否已经超过30秒.如果比30秒之前时间小，则保存时间超过30秒
            if(time.compareTo(beforeTime)<0){
                it.remove();
            }


        }

    }
}
